package com.util;

import com.config.DBConfig;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public final class DBUtil {
    private static String url;
    private static String username;
    private static String password;

    static {
        // 加载database驱动类
        // 获取类加载器
        // 获得指定文件的输入流
        Properties properties = new Properties();
        try (InputStream in = DBUtil.class.getClassLoader()
                .getResourceAsStream("application.properties");) {
            // 加载配置文件所代表的输入流
            properties.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            String driverClassName = properties.getProperty("datasource.driverclassName");
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        url = properties.getProperty("datasource.jdbcUrl");
        username = properties.getProperty("datasource.username");
        password = properties.getProperty("datasource.password");
    }

    private DBUtil() {}

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static void main(String[] args) {
        // 2. 使用DriverManager获取数据库连接
        try (
                Connection  connection = getConnection();
                Statement stmt = connection.createStatement();
                PreparedStatement preparedStmt = connection.prepareStatement("UPDATE users SET username=? WHERE userid=?")
        ) { // 申明AutoCloseable类型的对象
            DatabaseMetaData dbMetaData = connection.getMetaData();
            System.out.println(
                    String.format("数据库版本：%d.%d",
                            dbMetaData.getDatabaseMajorVersion(),
                            dbMetaData.getDatabaseMinorVersion()));
            System.out.println(String.format("数据库URL：%s", dbMetaData.getURL()));
            System.out.println(String.format("数据库连接用户名：%s", dbMetaData.getUserName()));

            // 3. 操作数据库，这里是查询
            ResultSet rs = stmt.executeQuery("select userid, username from users where username like 'admin%'");
            int i = 0;

            while(rs.next()) { // next用于将结果集的游标往下移动一个位置，返回结果代表移动后的位置有没有记录
                i++;
//            String email = rs.getString(3);
                System.out.println(String.format("第%d行：id：%d, username：%s", i,
                        rs.getLong("userid"),
                        rs.getString("username")));
//                        rs.getString("email"),
//                        rs.getString("phone")));
            }

            preparedStmt.setString(1, "admin");
            preparedStmt.setLong(2, 1L);
            preparedStmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}